package com.pn.taikao.service.impl;

import com.pn.taikao.common.ResultCode;
import com.pn.taikao.entity.StudentCourse;
import com.pn.taikao.entity.User;
import com.pn.taikao.exception.BusinessException;
import com.pn.taikao.mapper.StudentCourseMapper;
import com.pn.taikao.service.StudentCourseService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentCourseServiceImpl implements StudentCourseService {

    private final StudentCourseMapper studentCourseMapper;

    public StudentCourseServiceImpl(StudentCourseMapper studentCourseMapper) {
        this.studentCourseMapper = studentCourseMapper;
    }

    @Override
    public Long selectCourse(Long studentId, Long courseId) {
        // 检查是否已经选过该课程
        StudentCourse exist = studentCourseMapper.selectByStudentIdAndCourseId(studentId, courseId);
        if (exist != null) {
            throw new BusinessException(ResultCode.PARAM_ERROR, "已经选过该课程");
        }
        
        StudentCourse studentCourse = new StudentCourse();
        studentCourse.setStudentId(studentId);
        studentCourse.setCourseId(courseId);
        studentCourse.setCreateTime(LocalDateTime.now());
        studentCourse.setUpdateTime(LocalDateTime.now());
        studentCourseMapper.insert(studentCourse);
        return studentCourse.getId();
    }

    @Override
    public void unselectCourse(Long studentId, Long courseId) {
        studentCourseMapper.deleteByStudentIdAndCourseId(studentId, courseId);
    }

    @Override
    public boolean isSelected(Long studentId, Long courseId) {
        StudentCourse exist = studentCourseMapper.selectByStudentIdAndCourseId(studentId, courseId);
        return exist != null;
    }

    @Override
    public List<StudentCourse> getByStudentId(Long studentId) {
        return studentCourseMapper.selectByStudentId(studentId);
    }

    @Override
    public List<StudentCourse> getByCourseId(Long courseId) {
        return studentCourseMapper.selectByCourseId(courseId);
    }

    @Override
    public long countByStudentId(Long studentId) {
        return studentCourseMapper.countByStudentId(studentId);
    }

    @Override
    public long countByCourseId(Long courseId) {
        return studentCourseMapper.countByCourseId(courseId);
    }

    @Override
    public List<User> getStudentsByCourseId(Long courseId) {
        return studentCourseMapper.selectStudentsByCourseId(courseId);
    }
}
